package com.qingzhuge.web.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;
import java.util.Objects;

/**
 * @author : zero.xiao
 * @description : 国际化信息设置
 * @modified :
 */
@Component
public class LocaleInterceptor extends Interceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        Locale locale = request.getLocale();
        // 设置客户端语言
        if (locale == null) {
            String language = request.getHeader("language");
            if (StringUtils.isNotBlank(language)) {
                locale = new Locale(language);
                session.setAttribute("LOCALE", locale);
            } else {
                locale = Locale.CHINA;
            }
        }
        if (!Objects.equals(locale, Locale.CHINA)
                && !Objects.equals(locale, Locale.CHINESE)
                && !Objects.equals(locale, Locale.TRADITIONAL_CHINESE)
                && !Objects.equals(locale, Locale.ENGLISH)
                && !Objects.equals(locale, Locale.UK)
                && !Objects.equals(locale, Locale.US)
        ) {
            locale = Locale.CHINA;
        }
        LocaleContextHolder.setLocale(locale);
        return super.preHandle(request, response, handler);
    }
}
